package com.it.day8;

/**
 * ClassName: ThreadLocalDemo
 * Description: ThreadLocal演示多线程买票
 *
 * @Author: csx
 * @Create: 2025/5/15 - 9:32
 * @version: v1.0
 */

class House{
    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void saleHouse(){
        Integer value = threadLocal.get();
        threadLocal.set(++value);
    }
}

public class ThreadLocalDemo {
    public static void main(String[] args) {
        House house = new House();

        new Thread(() -> {
            try {
                for (int i = 0; i < 3; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName() + "\t----卖出：" + house.threadLocal.get());
            } finally {
                house.threadLocal.remove();
            }
        }, "t1").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName() + "\t----卖出：" + house.threadLocal.get());
            } finally {
                house.threadLocal.remove();
            }
        }, "t2").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 8; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName() + "\t----卖出：" + house.threadLocal.get());
            } finally {
                house.threadLocal.remove();
            }
        }, "t3").start();

        System.out.println(Thread.currentThread().getName() + "\t----卖出：" + house.threadLocal.get());
    }
}





